package com.study.demo01.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhuzi
 * 2023/12/20 20:39
 * 原文链接：<a href="https://blog.csdn.net/qq_41899248/article/details/126082489">批量处理消息</a>
 */
@Configuration
public class BatchConfig {


    @Bean("simpleRabbitListenerContainerFactory")
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setBatchListener(true); // 配置一个BatchMessageListenerAdapter
        factory.setConsumerBatchEnabled(true); // 允许创建批量消息
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);

        //每次接两条
        factory.setBatchSize(100);
        //5秒内没有数据再入队列，也执行
        factory.setReceiveTimeout(1000L * 5);
        return factory;
    }

}
